package com.demo.returned_message;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * 如何生效
 *  在yaml文件中配置spring.rabbitmq.publisher-returns: true  #消息发送后,如果发送失败,则会返回失败信息信息
 *  没有被正确路由到合适队列的消息也会回调该方法
 * @author shenguangyang
 */
@Component
public class MessageReturnsCallback implements RabbitTemplate.ReturnsCallback {
    private static final Logger log = LoggerFactory.getLogger(MessageReturnsCallback.class);

    /**
     * 当消息无法路由的时候的回调方法
     * @param returned the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        // 消息被回退
        log.warn("returnedMessage ==> message: {}, exchange: {}, routingKey: {}, replyCode: {}, replyText: {}",
                new String(returned.getMessage().getBody()),  returned.getExchange(), returned.getRoutingKey(),
                returned.getReplyCode(), returned.getReplyText());
    }
}
